package top.zhangjianyong.blog.factory;

import com.aliyun.sts20150401.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zhangjianyong.blog.config.sts.StsProperties;

/**
 * STS 客户端工厂
 * 
 * @author zhangjianyong
 * @since 2024-01-01
 */
@Slf4j
@Component
public class StsClientFactory {
    
    @Autowired
    private StsProperties stsProperties;
    
    private volatile Client stsClient;
    
    /**
     * 获取STS客户端实例（单例模式）
     * 
     * @return STS客户端
     * @throws Exception 创建客户端异常
     */
    public Client getStsClient() throws Exception {
        if (stsClient == null) {
            synchronized (this) {
                if (stsClient == null) {
                    stsClient = createStsClient();
                }
            }
        }
        return stsClient;
    }
    
    /**
     * 创建STS客户端
     * 
     * @return STS客户端
     * @throws Exception 创建客户端异常
     */
    private Client createStsClient() throws Exception {
        log.info("创建STS客户端，端点: {}", stsProperties.getEndpoint());
        
        Config config = new Config()
                .setAccessKeyId(stsProperties.getAccessKeyId())
                .setAccessKeySecret(stsProperties.getAccessKeySecret())
                .setEndpoint(stsProperties.getEndpoint());
        
        Client client = new Client(config);
        log.info("STS客户端创建成功");
        
        return client;
    }
    
    /**
     * 销毁客户端（用于测试或重新初始化）
     */
    public void destroyClient() {
        if (stsClient != null) {
            stsClient = null;
            log.info("STS客户端已销毁");
        }
    }
} 